package com.ebo.rongcloud.activitys;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.ebo.agora.openvcall.AGApplication;
import com.ebo.agora.openvcall.IBaseActivity;
import com.ebo.apicloud.H5Activity;
import com.ebo.download.download2.DownloadTestActivity;
import com.ebo.pay.PayActivity;
import com.ebo.rongcloud.models.MyUser;
import com.ebo.supervideoplayer.MyTestActivity;
import com.ebo.upload.UploadListActivity;
import com.ebo.xf.IseDemo;
import com.ebo.zxing.QrCodeActivity;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import http_utils.interfaces.IHttpPostListener;
import http_utils.utils.Ipost;
import http_utils.utils.URLs;
import io.agora.openvcall.R;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.UserInfo;
import utils.IToast;
import utils.Lg;


/**
 * Created by admin on 2017/4/7.
 */

public class ConversationLoginActivity extends IBaseActivity implements View.OnClickListener, RongIM.UserInfoProvider {

    Button btn_Login, btn_conversation, btn_vcall, btn_h5, btn_download, btn_supervideoplayer,btn_upload,btn_pay,btn_zxing,btn_xf;
    private static List<MyUser> userIdList;
    EditText et_input_userid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_conversationlogin);
//        initUserInfo();
        initViews();
    }

    void initViews() {
        btn_Login = (Button) findViewById(R.id.button);
        btn_Login.setOnClickListener(this);
        btn_conversation = (Button) findViewById(R.id.button2);
        btn_conversation.setOnClickListener(this);
        btn_conversation.setClickable(false);
        btn_vcall = (Button) findViewById(R.id.button3);
        btn_vcall.setOnClickListener(this);

        et_input_userid = (EditText) findViewById(R.id.et_input_uesrid);
        btn_h5 = (Button) findViewById(R.id.btn_h5);
        btn_h5.setOnClickListener(this);
        btn_download = (Button) findViewById(R.id.btn_download);
        btn_download.setOnClickListener(this);
        btn_supervideoplayer = (Button) findViewById(R.id.btn_supervideoplayer);
        btn_supervideoplayer.setOnClickListener(this);
        btn_upload = (Button)findViewById(R.id.btn_upload);
        btn_upload.setOnClickListener(this);
        btn_pay = (Button)findViewById(R.id.pay);
        btn_pay.setOnClickListener(this);
        btn_zxing = (Button)findViewById(R.id.btn_zxing);
        btn_zxing.setOnClickListener(this);
        btn_xf= (Button)findViewById(R.id.btn_xf);
        btn_xf.setOnClickListener(this);
    }

    //重写onKeyDown方法
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //判断当点击的是返回键
        if (keyCode == event.KEYCODE_BACK) {
            exit();//退出方法
        }
        return true;
    }

    private long time = 0;

    //退出方法
    private void exit() {
        //如果在两秒大于2秒
        if (System.currentTimeMillis() - time > 2000) {
            //获得当前的时间
            time = System.currentTimeMillis();
            show_Toast("再点击一次退出应用程序");
        } else {
            //点击在两秒以内
            removeALLActivity();//执行移除所以Activity方法
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:
                onClick_Login(v);
                break;
            case R.id.button2:
                onClick_Conversation(v);
                break;
            case R.id.button3:
//                startActivity(new Intent().setClass(this, MainActivity.class));
//                Intent i = new Intent().setClass(this, MainActivity.class);
//                i.putExtra("channel_name",channel_name);
//                i.putExtra("uid",uid);
//                startActivity(i);
                break;
            case R.id.btn_h5:
                Intent intent = new Intent(this, H5Activity.class);
                startActivity(intent);
                break;
            case R.id.btn_download:
                startActivity(new Intent().setClass(this, DownloadTestActivity.class));
                break;
            case R.id.btn_supervideoplayer:
                startActivity(new Intent().setClass(this, MyTestActivity.class));
                break;
            case R.id.btn_upload:
                startActivity(new Intent().setClass(this, UploadListActivity.class));
                break;
            case R.id.pay:
                startActivity(new Intent().setClass(this, PayActivity.class));
                break;
            case  R.id.btn_zxing:
                startActivity(new Intent().setClass(this, QrCodeActivity.class));
                break;
            case R.id.btn_xf:
                startActivity(new Intent().setClass(this, IseDemo.class));
                break;
        }
    }

    String channel_name = "1";
    String uid = "1";



    void onClick_Conversation(View v) {
        startActivity(new Intent(ConversationLoginActivity.this, HomeActivity.class));
    }

    void onClick_Login(View v) {
        String userid = et_input_userid.getText().toString();
        if (userid == null || userid.length() == 0) {
            return;
        }
        send_Lgoin(userid);

    }

    /**
     * <p>连接服务器，在整个应用程序全局，只需要调用一次，需在 {@link #/init(Context)} 之后调用。</p>
     * <p>如果调用此接口遇到连接失败，SDK 会自动启动重连机制进行最多10次重连，分别是1, 2, 4, 8, 16, 32, 64, 128, 256, 512秒后。
     * 在这之后如果仍没有连接成功，还会在当检测到设备网络状态变化时再次进行重连。</p>
     *
     * @param token     从服务端获取的用户身份令牌（Token）。
     * @param /callback 连接回调。
     * @return RongIM  客户端核心类的实例。
     */
    private void connect(String token) {

        if (getApplicationInfo().packageName.equals(AGApplication.getCurProcessName(getApplicationContext()))) {

            RongIM.connect(token, new RongIMClient.ConnectCallback() {

                /**
                 * Token 错误。可以从下面两点检查 1.  Token 是否过期，如果过期您需要向 App Server 重新请求一个新的 Token
                 *                  2.  token 对应的 appKey 和工程里设置的 appKey 是否一致
                 */
                @Override
                public void onTokenIncorrect() {
                    Toast.makeText(ConversationLoginActivity.this, "tokne错误", Toast.LENGTH_LONG).show();
                }

                /**
                 * 连接融云成功
                 * @param userid 当前 token 对应的用户 id
                 */
                @Override
                public void onSuccess(String userid) {
                    initUserInfo();
                    btn_Login.setText("登陆成功，userid=" + userid);
                    btn_conversation.setClickable(true);
                }

                /**
                 * 连接融云失败
                 * @param errorCode 错误码，可到官网 查看错误码对应的注释
                 */
                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {
                    btn_Login.setText("登陆失败，errorCode=" + errorCode);
                }
            });
        }
    }

    String userId, token, nickname, rongyun_portrait_uri;

    //登陆，获取token
    void send_Lgoin(String uid) {
        Map<String, Object> postParams = new HashMap<String, Object>();
        postParams.put("uid", uid);
        Ipost.send(this, URLs.RONG_GETTOKEN, postParams, new PostGetToken(), true);
    }

    class PostGetToken implements IHttpPostListener {
        @Override
        public void responseSuccess(String result) {
            if (Ipost.isTimeOut(ConversationLoginActivity.this, result)) {
                return;
            }
            if (null != result) {
                Lg.d("result=" + result);
                try {
                    JSONObject resultObject = new JSONObject(result);
                    int error = resultObject.getInt("error");
                    //code200(200为正常)",
                    int code = resultObject.getInt("code");
                    switch (code) {
                        //成功
                        case 200:
                            userId = resultObject.getString("userId");
                            token = resultObject.getString("token");
                            nickname = resultObject.getString("nickname");
                            rongyun_portrait_uri = resultObject.getString("rongyun_portrait_uri");
                            connect(token);
                            btn_Login.setEnabled(false);
                            break;
                        //其他失败文字提示
                        default:
                            IToast.show(ConversationLoginActivity.this, "登陆获取token失败");
                            break;
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    IToast.show(ConversationLoginActivity.this, "网络异常：\n" + e.toString());
                }
            }
        }
    }


    private void initUserInfo() {
        userIdList = new ArrayList<MyUser>();
        userIdList.add(new MyUser(userId, nickname, rongyun_portrait_uri));
        RongIM.setUserInfoProvider(this, true);

        if (RongIM.getInstance() != null) {
            Lg.d("initUserInfo success! userId=" + userId + ", nickname=" + nickname + " ,rongyun_portrait_uri=" + rongyun_portrait_uri);
            RongIM.getInstance().setCurrentUserInfo(new UserInfo(userId, nickname, Uri.parse(rongyun_portrait_uri)));
            RongIM.getInstance().setMessageAttachedUserInfo(true);
        } else {
            Lg.d("initUserInfo error");
        }
    }

    public static void insert_UserInfo(String userid, String nickname, String uri) {
        if (userIdList == null) {
            userIdList = new ArrayList<MyUser>();
        }
        userIdList.add(new MyUser(userid, nickname, uri));
    }


    @Override
    public UserInfo getUserInfo(String s) {
        if (userIdList == null) {
            return null;
        }
        for (MyUser i : userIdList) {
            if (i.getUserId().equals(s)) {
//                Log.e(TAG, i.getPortraitUri());
                return new UserInfo(i.getUserId(), i.getName(), Uri.parse(i.getPortraitUri()));
            }
        }
        Log.e("MainActivity", "UserId is : " + s);
        return null;
    }
}
